<template>
  <div class="activities-container">
    <div class="page-header">
      <h2 class="page-title">活动管理</h2>
<!--      <el-button type="primary" icon="el-icon-plus" @click="showActivityDialog">创建活动</el-button>-->
    </div>

    <!--    <div class="activity-filter">-->
    <!--      <el-select v-model="selectedType" placeholder="活动类型" clearable>-->
    <!--        <el-option-->
    <!--          v-for="type in activityTypes"-->
    <!--          :key="type.id"-->
    <!--          :label="type.name"-->
    <!--          :value="type.id"-->
    <!--        >-->
    <!--        </el-option>-->
    <!--      </el-select>-->
    <!--    </div>-->

    <el-tabs v-model="activeTab" class="activity-tabs">
      <el-tab-pane label="进行中" name="ongoing">
        <transition-group name="list" tag="div" class="activity-list">
          <div v-for="activity in ongoingActivities" :key="activity.id" class="activity-card">
            <div class="activity-header">
              <span class="activity-status" :class="getStatusClass(activity.status)">
                {{ getStatusText(activity.status) }}
              </span>
              <h3 class="activity-name">{{ activity.activityName }}</h3>
              <p class="activity-time">{{ activity.startTime }} - {{ activity.endTime }}</p>
            </div>
            <div class="activity-content">
              <div class="activity-info">
                <p><i class="el-icon-user"></i>参与人数：{{ activity.participantCount }}/{{ activity.maxParticipants }}人</p>
                <p><i class="el-icon-tickets"></i>活动名称：{{ activity.activityName }}</p>
                <p><i class="el-icon-location"></i>活动地点：{{ activity.schedule }}</p>
                <p><i class="el-icon-money"></i>活动预算：¥{{ activity.budget }}</p>
              </div>
              <div class="activity-progress">
                <el-progress type="circle" :percentage="activity.progress" :status="getProgressStatus(activity.progress)"></el-progress>
              </div>
            </div>
            <div class="activity-footer">
              <el-button type="text" @click="viewDetails(activity)">查看详情</el-button>
              <el-button type="primary" size="small" @click="joinActivity(activity)" :disabled="!canJoinActivity(activity)">{{ getJoinButtonText(activity) }}</el-button>
            </div>
          </div>
        </transition-group>
      </el-tab-pane>

      <el-tab-pane label="已结束" name="finished">
        <transition-group name="list" tag="div" class="activity-list">
          <div v-for="activity in finishedActivities" :key="activity.id" class="activity-card finished">
            <div class="activity-header">
              <span class="activity-status finished">已结束</span>
              <h3 class="activity-name">{{ activity.activityName }}</h3>
              <p class="activity-time">{{ activity.startTime }} - {{ activity.endTime }}</p>
            </div>
            <div class="activity-content">
              <div class="activity-info">
                <p><i class="el-icon-user"></i>参与人数：{{ activity.participantCount }}/{{ activity.maxParticipants }}人</p>
                <p><i class="el-icon-tickets"></i>活动名称：{{ activity.activityName }}</p>
                <p><i class="el-icon-location"></i>活动地点：{{ activity.schedule }}</p>
                <p><i class="el-icon-money"></i>活动预算：¥{{ activity.budget }}</p>

              </div>
            </div>
            <div class="activity-footer">
              <el-button type="text" @click="viewSummary(activity)">查看总结</el-button>
            </div>
          </div>
        </transition-group>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建活动对话框 -->
    <el-dialog
      title="创建活动"
      :visible.sync="dialogVisible"
      width="60%"
      class="activity-dialog"
    >
      <el-form :model="activityForm" :rules="rules" ref="activityForm" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="activityForm.name"></el-input>
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="activityForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动地点" prop="venue">
          <el-select v-model="activityForm.venue" placeholder="请选择活动地点">
            <el-option
              v-for="venue in venues"
              :key="venue.id"
              :label="venue.name"
              :value="venue.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动预算" prop="budget">
          <el-input-number v-model="activityForm.budget" :min="0" :step="100"></el-input-number>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            type="textarea"
            v-model="activityForm.description"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitActivity">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {addActivityParticipant, getActivityParticipantCount, getAllActivity} from "@/api/reunion/activity";

export default {
  name: 'Activities',
  data() {
    return {
      activeTab: 'ongoing',
      dialogVisible: false,
      dialogTitle: '创建活动',
      activityTypes: [
        { id: 1, name: '团建活动' },
        { id: 2, name: '培训会议' },
        { id: 3, name: '节日庆典' }
      ],
      ongoingActivities: [

      ],
      finishedActivities: [

      ],
      selectedType: '',
      activityForm: {
        name: '',
        timeRange: [],
        venue: '',
        budget: 0,
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        timeRange: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
        venue: [{ required: true, message: '请选择活动地点', trigger: 'change' }],
        budget: [{ required: true, message: '请输入活动预算', trigger: 'blur' }],
        description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }]
      },
      venues: [
        { id: 1, name: '阳光会议室' },
        { id: 2, name: '户外拓展基地' },
        { id: 3, name: '创意空间' }
      ]
    }
  },
  created() {
    this.getAllActivate()
  },
  watch: {
    // 移除对ongoingActivities的监听，避免重复调用getActivityParticipantCount
  },
  methods: {

    async getActivityParticipantCount(activate){
      try {
        const res = await getActivityParticipantCount(activate.id)
        console.log(res)
        if (res.code === 200) {
          // 使用Vue.set确保响应式更新
          this.$set(activate, 'participantCount', res.data)
        }
      } catch (error) {
        console.error('获取参与人数失败:', error)
      }
      return activate
    },
    async getAllActivate(){
      try {
        const response = await getAllActivity()
        // 先设置基本数据
        this.ongoingActivities = response.data.filter(activity => activity.status === 1 || activity.status === 0)
        this.finishedActivities = response.data.filter(activity => activity.status === 2)

        // 使用Promise.all等待所有参与人数加载完成
        const participantPromises = this.ongoingActivities.map(activity =>
          this.getActivityParticipantCount(activity)
        )

        // 等待所有异步操作完成
        await Promise.all(participantPromises)

        // 可选：也加载已结束活动的参与人数
        // const finishedPromises = this.finishedActivities.map(activity =>
        //   this.getActivityParticipantCount(activity)
        // )
        // await Promise.all(finishedPromises)
      } catch (error) {
        console.error('加载活动列表失败:', error)
        this.$message.error('加载活动列表失败，请刷新页面重试')
      }
    },
    getStatusClass(status) {
      return {
        'preparing': status === 0,
        'in-progress': status === 1
      }
    },
    getStatusText(status) {
      return status === 0 ? '筹备中' : '进行中'
    },
    getProgressStatus(progress) {
      if (progress < 30) return 'exception'
      if (progress < 70) return 'warning'
      return 'success'
    },
    showActivityDialog() {
      this.dialogTitle = '创建活动'
      this.dialogVisible = true
    },
    viewDetails(activity) {
      this.$router.push(`/activity/${activity.id}`)
    },
    getActivityTypeName(typeId) {
      const type = this.activityTypes.find(t => t.id === typeId)
      return type ? type.name : '未知类型'
    },
    canJoinActivity(activity) {
      return activity.participantCount < activity.maxParticipants && activity.status === 1
    },
    getJoinButtonText(activity) {
      if (activity.status === 0) return '未开始'
      if (activity.participantCount >= activity.maxParticipants) return '已满员'
      return '立即报名'
    },
    joinActivity(activity) {
      if (!this.canJoinActivity(activity)) return

      this.$confirm('确定要报名参加该活动吗？', '报名确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 调用报名API
        addActivityParticipant(activity.id).then(res => {
          if (res.code === 200){
            this.$message.success('报名成功')

          }
        })
      }).catch(() => {})
    },
    viewSummary(activity) {
      this.dialogTitle = '活动总结'
      this.activityForm = { ...activity }
      this.dialogVisible = true
    },
    submitActivity() {
      this.$refs.activityForm.validate(valid => {
        if (valid) {
          // 准备活动数据
          const activityData = {
            activityName: this.activityForm.name,
            startTime: this.activityForm.timeRange[0],
            endTime: this.activityForm.timeRange[1],
            venue: this.activityForm.venue,
            budget: this.activityForm.budget,
            description: this.activityForm.description,
            maxParticipants: 30, // 默认最大参与人数
            status: 0 // 默认为筹备中状态
          };

          // 调用创建活动API
          createActivity(activityData).then(res => {
            if (res.code === 200) {
              this.$message.success('活动创建成功');
              this.dialogVisible = false;
              // 刷新活动列表
              this.getAllActivate();
            } else {
              this.$message.error(res.message || '创建活动失败');
            }
          }).catch(err => {
            console.error('创建活动失败:', err);
            this.$message.error('创建活动失败，请稍后重试');
          });
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.activities-container {
  animation: fadeIn 0.5s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 500;
    color: #2c3e50;
    margin: 0;
  }
}

.activity-filter {
  margin-bottom: 20px;
  display: flex;
  gap: 16px;
  flex-wrap: wrap;

  .el-select {
    width: 200px;
  }
}

.activity-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.activity-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px 0;

  @media screen and (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.activity-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
  }

  &.finished {
    opacity: 0.8;
  }

  .el-button--primary.el-button--small {
    padding: 8px 20px;
    font-weight: 500;

    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }

  .activity-header {
    padding: 16px;
    background: #f5f7fa;
    border-bottom: 1px solid #ebeef5;

    .activity-status {
      display: inline-block;
      padding: 2px 8px;
      border-radius: 12px;
      font-size: 12px;
      color: white;
      margin-bottom: 8px;

      &.preparing {
        background: #e6a23c;
      }

      &.in-progress {
        background: #409eff;
      }

      &.finished {
        background: #909399;
      }
    }

    .activity-name {
      margin: 0 0 8px;
      font-size: 18px;
      color: #2c3e50;
    }

    .activity-time {
      margin: 0;
      font-size: 14px;
      color: #606266;
    }
  }

  .activity-content {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .activity-info {
      flex: 1;

      p {
        margin: 8px 0;
        color: #606266;
        font-size: 14px;

        i {
          margin-right: 8px;
          color: #909399;
        }
      }
    }

    .activity-progress {
      margin-left: 20px;
    }
  }

  .activity-footer {
    padding: 12px 16px;
    border-top: 1px solid #ebeef5;
    text-align: right;

    .el-button {
      margin-left: 12px;
    }
  }
}

// 列表动画
.list-enter-active, .list-leave-active {
  transition: all 0.5s;
}
.list-enter, .list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

// 页面动画
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.activity-dialog {
  .el-dialog__body {
    padding: 30px 20px;
  }
}
</style>
